<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'/goods'}">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 提示区域 -->
    <el-card class="box-card">
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"></el-alert>

      <!--步骤进度条-->
      <el-steps :active="activeName-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!--左侧边栏目-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-tabs
          v-model="activeName"
          @tab-click="tabClicked"
          tab-position="left"
          :before-leave="tabBeforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="catList"
                v-model="addForm.goods_cat"
                :props="catProps"
                @change="catChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyParams" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item2"
                  :key="i2+''+Math.random()"
                  v-for="(item2,i2) in item.attr_vals"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParams"
              :key="item.attr_id"
              label-width="150px"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="uploadPreview"
              :on-remove="uploadRemove"
              :on-success="uploadSuccess"
              list-type="picture"
              :headers="uploadParam"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"></quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 图片预览 -->
      <el-dialog title="提示" :visible.sync="previewVisible" width="50%">
        <img :src="previewImg" alt class="img-preview">
      </el-dialog>
      <!--end-->
    </el-card>
  </div>
</template>

<script>
import config from '../../config.json'

// 导入富文本编辑器相关
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

// 导入lodash
import _ from 'lodash'

export default {
  components: {
    // 富文本编辑器组件
    quillEditor
  },
  data() {
    return {
      // 侧边栏 steps进度条 激活设定
      activeName: '0',

      /** 添加商品部分1 */
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选取商品分类', trigger: 'blur' }
        ]
      },

      // 供选取的三级商品分类信息
      catList: [],
      // 级联三级分类项目参数
      catProps: {
        value: 'cat_id',
        label: 'cat_name'
      },
      // 获取当前选取的第三级分类id
      threeCatId: 0,
      // 商品参数
      manyParams: [],
      // 商品属性
      onlyParams: [],
      // 上传图片服务器地址
      uploadUrl: config.baseURL + 'upload',
      // 上传图片需要的参数
      uploadParam: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片路径名
      previewImg: '',
      // 预览图片dialog开关
      previewVisible: false
      /** 添加商品部分2 */
    }
  },
  created() {
    this.getCatList()
  },
  methods: {
    // 添加商品处理
    addGoods() {
      // 表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 把addForm复制一份，并对复制品进行操作
          var form = _.cloneDeep(this.addForm)
          form.goods_cat = form.goods_cat.join(',')

          // 处理 动态参数 信息
          this.manyParams.forEach(item => {
            if (item.attr_vals.length > 0) {
              var newobj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(' ')
              }
              form.attrs.push(newobj)
            }
          })

          // 处理 静态属性 信息
          this.onlyParams.forEach(item => {
            if (item.attr_vals.trim()) {
              var newobj = { attr_id: item.attr_id, attr_value: item.attr_vals }
              form.attrs.push(newobj)
            }
          })

          // 把数据提交给服务器存储
          const { data: res } = await this.$http.post('goods', form)

          if (res.meta.status !== 201) {
            return this.$message({
              message: res.meta.msg,
              type: 'error',
              duration: 1500
            })
          }

          // 提示
          this.$message({
            message: res.meta.msg,
            type: 'success',
            duration: 1500
          })
          // 页面跳转
          this.$router.push('goods')
          // console.log(form)
        }
      })
    },

    // 上传图片成功
    uploadSuccess(result) {
      if (result.meta.status !== 200) {
        return this.$message({
          message: '图片上传失败',
          type: 'error',
          duration: 1500
        })
      }

      // console.log(result)
      // 把图片路径名通过对象形式存储给addForm.pics成员
      var o = { pic: result.data.tmp_path }
      this.addForm.pics.push(o)
    },
    // 预览上传图片
    uploadPreview(result) {
      // 被预览图片路径名
      this.previewImg = result.response.data.url
      // dialog弹层开关
      this.previewVisible = true
    },
    // 删除上传图片
    uploadRemove(result) {
      if (result.response.meta.status !== 200) {
        return this.$message({
          message: '图片删除失败',
          type: 'error',
          duration: 1500
        })
      }

      // 从pics中获取被删除所在的下标
      var i = this.addForm.pics.findIndex(item => {
        return item.pic === result.response.data.tmp_path
      })
      // 把图片路径名从pics中删除
      this.addForm.pics.splice(i, 1)
    },

    // 侧边栏 点击事件
    async tabClicked(tab, event) {
      // 判断点击了“商品参数”标签就根据分类获取对应的参数信息
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.threeCatId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )

        if (res.meta.status !== 200) {
          return this.$message({
            message: '获取商品参数失败',
            type: 'error',
            duration: 1500
          })
        }

        // 把attr_vals由空格分割的字符串 变为数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })

        this.manyParams = res.data
      } else if (this.activeName === '2') {
        // 判断点击了“商品属性”标签，就获取对应的属性信息
        const { data: res } = await this.$http.get(
          `categories/${this.threeCatId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )

        if (res.meta.status !== 200) {
          return this.$message({
            message: '获取商品属性失败',
            type: 'error',
            duration: 1500
          })
        }
        // console.log(res)
        this.onlyParams = res.data
      }
    },
    // 获取供选取的商品三级分类信息
    async getCatList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })

      if (res.meta.status !== 200) {
        return this.$message({
          message: '三级商品分类获取失败',
          type: 'error',
          duration: 1500
        })
      }
      // console.log(res.data)
      this.catList = res.data
    },

    // 鼠标选取第三级分类触发调用
    catChange() {
      // 禁止选取非三级分类
      if (this.addForm.goods_cat.length === 3) {
        // console.log(this.addForm)
        // 维护第三级分类id
        this.threeCatId = this.addForm.goods_cat[2]
      } else {
        // 设置不选取任何项目
        this.threeCatId = 0
        this.addForm.goods_cat = []
      }
    },

    // 标签切换之前处理
    tabBeforeLeave(newTab, oldTab) {
      if (oldTab === '0' && this.threeCatId === 0) {
        this.$message({
          message: '请选取第三级商品分类',
          type: 'error',
          duration: 1500
        })
        return false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps,
.el-tabs {
  margin-top: 20px;
}
// 预览图片img标签样式
.img-preview {
  width: 100%;
}
.quill-editor {
  margin-bottom: 15px;
}
</style>
